package com.xopencode.netty.heima;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Mcb
 * @date 2022/5/17
 * @apiNote 测试EventLoop的io任务
 */
@Slf4j
public class EventLoopIoServer {
    public static void main(String[] args) {
        EventLoopGroup group = new DefaultEventLoopGroup();
        NioEventLoopGroup bossEvenLoopGroup = new NioEventLoopGroup();
        NioEventLoopGroup childEvenLoopGroup = new NioEventLoopGroup();
        new ServerBootstrap()
                .group(bossEvenLoopGroup, childEvenLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //handler1使用默认 childGroup
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter() { //通道入站处理程序适配器
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(CharsetUtil.UTF_8));
                                //让消息传递到下一个 TODO 了解fireChannelRead
                                ctx.fireChannelRead(msg);
                            }
                        }).addLast(group,"handler2",new ChannelInboundHandlerAdapter() { //handler2使用额外事件组执行
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                log.debug(byteBuf.toString(CharsetUtil.UTF_8));
                            }
                        });
                    }
                }).bind(9090);
    }
}
